package dice.sinanya.dice.system;

import dice.sinanya.start.FindDir;
import dice.sinanya.system.MessagesSystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import static dice.sinanya.system.MessagesSystem.STR_BOT_VERSIONS;
import static dice.sinanya.system.MessagesSystem.devInfo;
import static dice.sinanya.tools.checkdata.CheckCosInNet.checkCostInNet;
import static dice.sinanya.tools.getinfo.GetMessagesProperties.entitySystemProperties;


public class DevInfo implements FindDir {

    public void initDevInfo() throws IOException {
        devInfo.setBotInfo(STR_BOT_VERSIONS.toString());
        if (checkCostInNet("dice-6-1256090486.cos.ap-beijing.myqcloud.com/")) {
            devInfo.setUpdateAddress("https://dice-7-1256090486.cos.ap-beijing.myqcloud.com");
        } else {
            devInfo.setUpdateAddress("https://dice-7-1256090486.file.myqcloud.com");
        }
        java.util.Properties pps = new java.util.Properties();
        File devInfoYaml = findDir("devInfo.properties");
        if (devInfoYaml == null) {
            return;
        }
        try (FileInputStream devInfoInput = new FileInputStream(devInfoYaml)) {
            try (InputStreamReader reader = new InputStreamReader(devInfoInput, StandardCharsets.UTF_8)) {
                pps.load(reader);
            }
        }
        devInfo.setUpdateAddress(pps.getProperty("updateAddress", devInfo.getUpdateAddress()));
        MessagesSystem.VERSIONS = pps.getProperty("version", MessagesSystem.VERSIONS);
        String botInfo;
        if (pps.contains("botInfo")) {
            botInfo = pps.getProperty("botInfo") + "当前版本号为:\t" +
                    MessagesSystem.VERSIONS +
                    "\n最新版本号为:\t" +
                    "%s" +
                    "\n项目文档:\thttps://sinanya.com/#/" +
                    "\n交流及BUG反馈群:\t162279609" +
                    "\n交流反馈论坛（请勿讨论非开发相关话题）:\thttps://sinanya.com/discuz/forum.php" +
                    "\n反馈问题命令请参阅.man send的说明" +
                    "\n对塔骰进行投喂，帮助塔骰走的更远:https://afdian.net/@sitanya233" +
                    "\n" +
                    entitySystemProperties.getBotInfo("0");
        } else {
            botInfo = STR_BOT_VERSIONS.toString();
        }
        devInfo.setBotInfo(botInfo);
    }

    @Override
    public File findDir(String fileName) throws IOException {
        File myDir = findMyDir();
        File devInfo = new File(URLDecoder.decode(myDir.getPath(), "UTF-8"));
        if (devInfo.exists() && devInfo.isDirectory()) {
            File result = new File(URLDecoder.decode(devInfo.getPath(), "UTF-8"), "SinaNya" + File.separator + "conf" + File.separator + fileName);
            if (result.exists() && result.isFile()) {
                return result;
            }
        }
        return null;
    }
}
